package com.hmsm.sys.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.struts2.interceptor.SessionAware;
import org.springframework.web.servlet.ModelAndView;

import com.hmsm.server.base.BaseAction;
import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.bean.LocalUser;
import com.hmsm.sys.bean.RTXDeptBean;
import com.hmsm.sys.controller.RoleController;
import com.hmsm.sys.po.RoleInfo;

/**
 * 用户角色管理
 * 
 * @author 舒俊
 *
 *@version 1.0, 2012-11-29 下午04:25:02
 */
public class UserRoleAction extends BaseAction implements SessionAware {
	
	/**
	 * @since Ver 1.1
	 */
	
	private static final long serialVersionUID = 4626457218113669248L;
	
	@Resource
	private RoleController roleController;

	@Resource
	private OrgTreeHelper orgTreeHelper;

	private Map<String, Object> session;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	private Integer id;

	private String nodeType;

	public String getId() {
		return nodeType+id;
	}

	public void setId(String id) {
		if (id!=null){
			String[] strList = id.split("-");
			if (strList.length>0){
				nodeType=strList[0].toLowerCase();
			}
			if (strList.length>1){
				this.id=Integer.parseInt(strList[1]);
			}
		}
	}

	private int userId;//用户编号

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	private int roleId;//角色ID

	public Integer getRoleId() {
		Integer roleId = null;
		if (role!=null){
			roleId = role.getPkId();
		}
		return roleId;
	}

	public void setRoleId(int roleId) {
		this.roleId = roleId;
		if (role==null){
			role = new RoleInfo(roleId);
		}else{
			role.setPkId(roleId);
		}
	}

	private int state;//角色ID集

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}
	
	private Integer orgId;
	
	public Integer getOrgId() {
		return orgId;
	}

	public void setOrgId(Integer orgId) {
		this.orgId = orgId;
	}

	private List<LocalDept> managedOrgList;

	public List<LocalDept> getManagedOrgList() {
		return managedOrgList;
	}

	public void setManagedOrgList(List<LocalDept> managedOrgList) {
		this.managedOrgList = managedOrgList;
	}

	private RoleInfo role;//角色

	public RoleInfo getRole() {
		role = (RoleInfo) session.get("role");
		if(role==null){
		}
		return role;
	}

	public void setRole(RoleInfo role) {
		this.role = role;
	}

	private String userIds;//用户ID集
	public String getUserIds() {
		return userIds;
	}

	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}

	private String roleIds;//角色ID集
	public String getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(String roleIds) {
		this.roleIds = roleIds;
	}

	private Set<Integer> roleUserIds;

	public Set<Integer> getRoleUserIds() {
		roleUserIds = new HashSet<Integer>();
		for(LocalUser user:getUserList()){
			roleUserIds.add(user.getPkId());
		}
		return roleUserIds;
	}

	private List<LocalUser> userList;//用户列表

	public List<LocalUser> getUserList() {
		LocalUser currentUser = getSessionUser();
		
		userList = (List<LocalUser>) session.get("roleUserList");
		if (userList==null){
			userList = new ArrayList<LocalUser>();
			session.put("roleUserList", userList);
		}
		return userList;
	}

	public void setUserList(List<LocalUser> userList) {
		this.userList = userList;
	}

	/**
	 * 角色授权用户管理
	 * @return
	 */
	public String manage(){
		LocalUser currentUser = getSessionUser();
		
		Integer roleId = getRoleId();
		if (roleId==null||roleId<=0){
			addActionError("未指定要授权的角色！");
			return ERROR;
		}
		RTXDeptBean rootDept = orgTreeHelper.getRootDept(orgTreeHelper.getOrgManageRight(), true, currentUser);
		session.put(OrgTreeHelper.ROOT_KEY, rootDept);

		ModelAndView modelAndView = roleController.edit(roleId, currentUser, getRequest());
		if(SUCCESS.equals(modelAndView.getViewName())){
			role = (RoleInfo) modelAndView.getModel().get("role");
			session.put("role", role);
			boolean isAdmin = (Boolean) modelAndView.getModel().get("isAdmin");
			managedOrgList = (List<LocalDept>) modelAndView.getModel().get(RoleController.MANAGED_ORG_LIST);
			mapResult.put("isAdmin", isAdmin);

			userList = (List<LocalUser>) modelAndView.getModel().get("userList");
			session.put("roleUserList", userList);
			
		}else{
			message = (String) modelAndView.getModel().get("errorMessage");
			addActionError(message);
		}
		
		return modelAndView.getViewName();
	}
	
	/**
	 * 添加角色用户授权选择树
	 * @return
	 */
	public String userSelect(){
		LocalUser currentUser = getSessionUser();
		
		Integer roleId = getRoleId();
		
		role = (RoleInfo) getRoleInfoService().getById(roleId);
		session.put("role", role);
		return SUCCESS;
	}
	
	/**
	 * action 加载子节点
	 * @return
	 */
	public String loadSubNodes(){
		LocalUser currentUser = getSessionUser();
		
		RTXDeptBean rootDept = (RTXDeptBean)session.get(OrgTreeHelper.ROOT_KEY);
		if (rootDept==null){
			this.addActionError("组织机构树未初始化！");
			return ERROR;
		}
		orgTreeHelper.setRootDept(rootDept, currentUser);
		try {
			List<JSONObject> list;
			if ("o".equalsIgnoreCase(nodeType)&&id!=null){
				list = orgTreeHelper.getSubNode(id, LocalUser.class, getRoleUserIds(), true, 1, currentUser);
			}else{
				list = orgTreeHelper.getSubNode(null, LocalUser.class, getRoleUserIds(), true, 1, currentUser);
			}
			for(JSONObject subNode:list){
				listResult.add(subNode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "arrayJson";
	}
	
	/**
	 * 解除用户角色关系
	 * 
	 * @author 舒俊
	 */
	public void del(){
		try {
			getRoleInfoService().unbindUserRoleRelation(getRoleId(), userId);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeResponse("-1");
		}
		this.writeResponse("1");
	}
	
	/**
	 * 保存用户、角色关联信息
	 * @return
	 * @author 舒俊
	 */
	public String saveRoleUsers(){
		LocalUser currentUser = getSessionUser();
		ModelAndView modelAndView = roleController.saveRoleUsers(roleId, "", userIds, currentUser, getRequest());
		if(SUCCESS.equals(modelAndView.getViewName())){
			mapResult.put("success", true);
		}else{
			mapResult.put("success", false);
			mapResult.put("errorMessage", modelAndView.getModel().get("errorMessage"));
		}
		return "json";
	}
	
	/**
	 * 保存角色、用户关联信息
	 * @return
	 * @author 舒俊
	 */
	public String addRoleUser(){
		String[] roleIdStr =  roleIds.split(",");
		try {
			for(int i=0;i<roleIdStr.length;i++){
				getRoleInfoService().bindUserRoleRelation(userId, Integer.parseInt(roleIdStr[i]));
			}
//			CommonUtil.userFuncMap = getRoleInfoService().initUserFunc();
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("发生错误："+e);
			return ERROR;
		}
		return SUCCESS;
	}
	
}
